import request from "@/utils/request"
import { createSlice } from "@reduxjs/toolkit"

export const article = createSlice({
  name: 'article',

  initialState: {
    channelList: [],
    articleList: [],
    query: {
      count: 0,
      page: 1,
      pageSize: 10
    }
  },

  reducers: {
    setChannelList(preState, action) {
      preState.channelList = action.payload
    },

    setArticleList(preState, action) {
      preState.articleList = action.payload.results
      preState.query = {
        count: action.payload.total_count,
        page: action.payload.page,
        pageSize: action.payload.per_page
      }
    }
  }
})

export const { setChannelList, setArticleList } = article.actions

export function getChannelAction() {
  return async (dispatch) => {
    const { data: { data: { channels } } } = await request.get('/channels')
    dispatch(setChannelList(channels))
  }
}

export function getArticleAction(params) {
  return async (dispatch) => {
    const { data: { data } } = await request.get('/mp/articles', { params })
    dispatch(setArticleList(data))
  }
}

export function deleteArticle(id, params) {
  return async dispatch => {
    await request.delete(`/mp/articles/${id}`)
    dispatch(getArticleAction(params))
  }
}

export function updateArticleAction(data, draft, isEdit) {
  return async () => {
    if (isEdit) {
      // 编辑
      await request.put(`/mp/articles/${data.id}?draft=${draft ? 'true' : 'false'}`, data)
    } else {
      await request.post(`/mp/articles?draft=${draft ? 'true' : 'false'}`, data)
    }
  }
}


export default article.reducer